package cn.b.sky.mes.pp.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.pp.enums.ProductionControlStatusCode;
import cn.b.sky.mes.pp.model.OrderType;
import cn.b.sky.mes.pp.model.ProductionConfirm;
import cn.b.sky.mes.pp.model.ProductionConfirmDetail;
import cn.b.sky.mes.pp.model.ProductionControl;
import cn.b.sky.mes.pp.model.condition.ProductionConfirmDetailCondition;
import cn.b.sky.mes.pp.model.condition.ProductionControlCondition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.cm.model.ProcessOperation;
import cn.b.sky.mes.cm.service.ProcessService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;
import cn.b.sky.mes.pp.service.OrderTypeService;
import cn.b.sky.mes.pp.service.ProductionConfirmDetailService;
import cn.b.sky.mes.pp.service.ProductionControlService;
import cn.b.sky.mes.pp.service.ProductionOrderConfirmService;
import cn.b.sky.mes.pp.service.ProductionOrderService;

@Controller
@RequestMapping("/productionControl/*")
public class ProductionControlController extends SecurityController {

  @Resource
  ECodeService eCodeService;

  @Resource
  OrderTypeService orderTypeService;

  @Resource
  ProductionControlService productionControlService;

  @Resource
  ProductionOrderConfirmService productionOrderConfirmService;

  @Resource
  ProductionOrderService orderService;

  @Resource
  ProductionConfirmDetailService productionConfirmDetailService;

  @Resource
  ProcessService processService;

  /**
   * 
   * <strong>Title : productionControlList<br></strong>
   * <strong>Description : </strong>生产管理号主页面<br> 
   * <strong>Create on : 2016年5月16日 下午1:32:25<br></strong>
   * <p>
   * @param navTabId
   * @param condition
   * @param model
   * @return
   * String
   * @throws 
   * @author zhaoxin01<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("productionControlList")
  public String productionControlList(String navTabId,
                                      @ModelAttribute("condition") ProductionControlCondition condition, Model model) {
    condition.setSiteCode(this.getSiteCode());
    if (StringUtils.isEmpty(condition.getOrderField())) {
      condition.setOrderField("productionControlNum");
    }
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    //订单类型
    List<OrderType> orderTypes = orderTypeService.getAllOrderTypes(this.getSiteCode());
    model.addAttribute("orderTypes", orderTypes);
    condition.setSiteCode(getSiteCode());
    condition.setData(productionControlService.selectProductionControlByCondition(condition));
    condition.setTotalCount(productionControlService.selectProductionControlCount(condition));
    model.addAttribute("page", condition);
    model.addAttribute("orderStatusECode", ecode);
    model.addAttribute(NAVTABID, navTabId);
    return "pp/productionControl/productionControl_list";
  }

  /**
   * 
   * <strong>Title : productionControlView<br></strong>
   * <strong>Description : </strong>详情<br> 
   * <strong>Create on : 2016年5月16日 下午3:15:13<br></strong>
   * <p>
   * @param navTabId
   * @param id
   * @param model
   * @return
   * String
   * @throws 
   * @author zhaoxin01<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("productionControlView")
  public String productionControlView(String navTabId, String id, Model model) {
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("orderStatusECode", ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("productionControl", productionControlService.selectProductionControl(getSiteCode(), id));
    return "pp/productionControl/productionControl_view";
  }

  /**
   * 
   * <strong>Title : deleteProductionControl<br></strong>
   * <strong>Description : </strong>删除<br> 
   * <strong>Create on : 2016年5月16日 下午4:00:17<br></strong>
   * <p>
   * @param model
   * @param navTabId
   * @param request
   * @return
   * DWZResult
   * @throws 
   * @author zhaoxin01<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("deleteProductionControl")
  @ResponseBody
  public DWZResult deleteProductionControl(Model model, String navTabId, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = productionControlService.deleteProductionControl(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

  /**
   * 
   * <strong>Title : placeOrderProductionControl<br></strong>
   * <strong>Description : </strong>投产<br> 
   * <strong>Create on : 2016年5月17日 下午3:06:13<br></strong>
   * <p>
   * @param model
   * @param navTabId
   * @param request
   * @return
   * DWZResult
   * @throws 
   * @author zhaoxin01<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("placeOrderProductionControl")
  @ResponseBody
  public DWZResult placeOrderProductionControl(Model model, String navTabId, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = productionControlService.doPlaceOrderProductionControl(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

  /**
   * 
   * <strong>Title : closeProductionControl<br></strong>
   * <strong>Description : </strong>强制关闭<br> 
   * <strong>Create on : 2016年5月17日 下午3:08:17<br></strong>
   * <p>
   * @param model
   * @param navTabId
   * @param request
   * @return
   * DWZResult
   * @throws 
   * @author zhaoxin01<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("closeProductionControl")
  @ResponseBody
  public DWZResult closeProductionControl(Model model, String navTabId, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = productionControlService.doCloseProductionControl(getSiteCode(), res, true);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

  /**
   * 
   * <strong>Title : productionArchives<br></strong>
   * <strong>Description : </strong>生产管理号订单档案<br> 
   * <strong>Create on : 2016-5-24 上午11:19:00<br></strong>
   * <p>
   * @param productionNum
   * @param model
   * @param navTabId
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "controlArchives")
  public String productionArchives(String productionControlNum, Model model, String navTabId) {
    if (!StringUtils.isBlank(productionControlNum)) {
      ProductionControl order = productionControlService.selectProductionControl(this.getSiteCode(),
          productionControlNum);
      if (order != null) {
        model.addAttribute("operationArchives",
            orderService.drawProcessOperation(this.getSiteCode(), order.getProcessCode(), order.getProcessRev()));
        model.addAttribute("productionControl", order);
      }
      //报工信息
      ProductionConfirmDetailCondition condition = new ProductionConfirmDetailCondition();
      condition.setSiteCode(this.getSiteCode());
      condition.setControlNum(productionControlNum);
      List<ProductionConfirmDetail> prodcutionOrderDetail = productionConfirmDetailService
          .selectSubmitDetailList(condition);
      int count = productionConfirmDetailService.getSubmitDetailCount(condition);
      condition.setData(prodcutionOrderDetail);
      condition.setTotalCount(count);
      model.addAttribute("page", condition);
    }

    model.addAttribute("productionControlNum", productionControlNum);
    model.addAttribute(NAVTABID, navTabId);
    return "/pp/productionControlArchives/productionControl_archives";
  }

  /**
   * 
   * <strong>Title : confirmProductionControl<br></strong>
   * <strong>Description : </strong>生产确认（仅供压力测试使用）<br> 
   * <strong>Create on : 2016年7月12日 下午2:52:10<br></strong>
   * <p>
   * @param model
   * @param navTabId
   * @param productionConfirm
   * @param request
   * @return
   * DWZResult
   * @throws 
   * @author zhaoxin01<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("confirmProductionControl")
  @ResponseBody
  public DWZResult confirmProductionControl(Model model, String navTabId, ProductionConfirm productionConfirm,
      HttpServletRequest request) {
    if (productionConfirm == null) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    List<ProductionConfirm> confirmList = new ArrayList<ProductionConfirm>();
    confirmList.add(productionConfirm);
    productionOrderConfirmService.doConfirmProduction(confirmList);
    return navTabAjaxDone(navTabId, null, null, null, "报工成功", null);

  }

  @RequestMapping("productionControlProductList")
  public String productionControlProductList(String navTabId,
      @ModelAttribute("condition") ProductionControlCondition condition, Model model) {
    condition.setSiteCode(this.getSiteCode());
    condition.setStatuseCode(ProductionControlStatusCode.CREATE.getValue());
    condition.setOperationScheduleFlag(0);
    if (StringUtils.isEmpty(condition.getOrderField())) {
      condition.setOrderField("productionControlNum");
    }
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    //订单类型
    List<OrderType> orderTypes = orderTypeService.getAllOrderTypes(this.getSiteCode());
    model.addAttribute("orderTypes", orderTypes);
    condition.setSiteCode(getSiteCode());
    condition.setData(productionControlService.selectProductionControlByCondition(condition));
    condition.setTotalCount(productionControlService.selectProductionControlCount(condition));
    model.addAttribute("page", condition);
    model.addAttribute("orderStatusECode", ecode);
    model.addAttribute(NAVTABID, navTabId);
    return "pp/productionControl/productionControl_intoProduct";
  }

  @RequestMapping("productionControlLookUp")
  public String productionControlLookUp(String navTabId,
      @ModelAttribute("condition") ProductionControlCondition condition, Model model, String workcenterCode) {
    condition.setSiteCode(this.getSiteCode());
    if (StringUtils.isEmpty(condition.getOrderField())) {
      condition.setOrderField("productionControlNum");
    }
    if (!StringUtils.isEmpty(workcenterCode)) {
      condition.setWorkCenterCode(workcenterCode);
    }
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    //订单类型
    List<OrderType> orderTypes = orderTypeService.getAllOrderTypes(this.getSiteCode());
    model.addAttribute("orderTypes", orderTypes);
    condition.setSiteCode(getSiteCode());
    condition.setData(productionControlService.selectProductionControlByCondition(condition));
    condition.setTotalCount(productionControlService.selectProductionControlCount(condition));
    model.addAttribute("page", condition);
    model.addAttribute("orderStatusECode", ecode);
    model.addAttribute(NAVTABID, navTabId);
    return "pp/productionControl/productionControl_lookup";
  }

  @RequestMapping("validateProductionControl")
  @ResponseBody
  public boolean validateSupplier(Model model, String navTabId, String productionControlNum, String workcenterCode) {
    ProductionControl productionControl = productionControlService.selectProductionControl(getSiteCode(),
        productionControlNum);
    boolean isExist = false;
    if (productionControl != null) {
      if (!StringUtils.isEmpty(workcenterCode)) {
        if (workcenterCode.equals(productionControl.getWorkCenterCode())) {
          isExist = true;
        }
      } else {
        isExist = true;
      }
    }
    return isExist;
  }

  @RequestMapping("productionControlSuggest")
  @ResponseBody
  public Object productionControlSuggest(
      @ModelAttribute("condition") ProductionControlCondition productionControlCondition, String workcenterCode) {
    productionControlCondition.setSiteCode(this.getSiteCode());
    productionControlCondition.setOrderField("productionControlNum");
    if (!StringUtils.isBlank(workcenterCode)) {
      productionControlCondition.setWorkCenterCode(workcenterCode);
    }
    return productionControlService.selectProductionControlByCondition(productionControlCondition);
  }

  @RequestMapping(value = "productionControlChange")
  @ResponseBody
  public List<ProcessOperation> productionControlChange(Model model, String navTabId, String id,
      String productionControlNum, HttpServletRequest request) {
    List<ProcessOperation> operas = new ArrayList<ProcessOperation>();
    if (!StringUtils.isEmpty(productionControlNum)) {
      ProductionControl productionControl = productionControlService.selectProductionControl(getSiteCode(),
          productionControlNum);
      if (productionControl != null) {
        operas = processService.selectProcessOperationByProcess(productionControl.getSiteCode(),
            productionControl.getProcessCode(), productionControl.getProcessRev());
      }
    }
    return operas;
  }
}